"""
@Project ：HD_project 
@File    ：demo1.py
@IDE     ：PyCharm 
@Author  ：靓仔
@Date    ：2023/12/13 0013 17:20 
"""
"""
@Project ：HD_project 
@File    ：tem_plan.py
@IDE     ：PyCharm 
@Author  ：靓仔
@Date    ：2023/12/13 0013 9:08 
"""
import json
from urllib.parse import urljoin
import requests


class JapdApi:
    BASE_URL = "http://10.6.10.110/"

    def __init__(self):
        self.session = requests.Session()
        self.headers = {
            'Host': '10.6.10.110',
            'Origin': 'http://10.6.10.110',
            'Ratio': '960*1707',
            'Referer': 'http://10.6.10.110/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.81'
        }
        self.token = self.session_login()
        self.user_id = self.session_login()
        self.get_pant = self.get_pant_info()
        self.todo_id = self.get_temporary_plan_id()
        self.todo_by_todo_id = self.query_todo_by_todo_id()
        self.next_activit = self.get_next_plan_info()

    def session_login(self):
        url = urljoin(self.BASE_URL, "jadp-api/auth/session")
        data = {"account": "yanzhi", "password": "DZDR1M81FcALjaYAXpRv/nSA2kYcWRXemwE09Txa1AU="}
        res = json.loads(self.session.post(url=url, json=data, headers=self.headers).text)
        res = res["result"]["data"]["user"]["userId"]
        return res

    # 获取当前用户下的所有待办信息
    def get_pant_info(self):
        _url = urljoin(self.BASE_URL, "bd-grsx-api/todo/page/collapse")
        data = {"bllx": "2", "userId": self.user_id, "xtbs": "10011006"}
        res = json.loads(self.session.post(url=_url, json=data, headers=self.headers).text)
        return res

    def get_temporary_plan_id(self):
        todo_id_list = []
        tem_plan_id = self.get_pant["result"][1]
        for todo_id in tem_plan_id["datas"]["list"]:
            todo_id_list.append(todo_id["id"])
        return todo_id_list

    # 提交临时计划部门内审核
    def bmnsh_plan(self):
        for todo in self.todo_id:
            url = urljoin(self.BASE_URL, "zdgl-api/common/submit")
            data = {"xtbs": "10011006", "docType": "4", "data": {"nextParticipantMap": {f"{self.next_activit}_user": [
                {"id": "8D37B6FC4AA847B3B4055435B92DEDA1", "name": "颜值", "typeCode": "person", "bllx": "2",
                 "role": "主办部门负责人", "dblx": ""}]}, "nextActivityDefId": self.next_activit, "spyj": "",
                "spjg": "1", "operateType": "2",
                "todoId": todo, "sfyy": "1",
                "extend": "{\"bmhqList\":[]}", "ywbs": "100",
                "sccldry": "", "pbzlc": ""}}
            res = json.loads(self.session.post(url=url, json=data, headers=self.headers).text)
            if res["code"] == 200:
                print("提交成功！")
            else:
                print("没有数据！")

    def queryTodoBytodoId_info(self, search_value):
        value = self.todo_by_todo_id["result"][search_value]
        return value

    def query_todo_by_todo_id(self):
        for todo in self.todo_id:
            url = urljoin(self.BASE_URL, f"bd-grsx-api/todo/queryTodoBytodoId/{todo}")
            res = json.loads(self.session.post(url=url, json="", headers=self.headers).text)
            return res

    # 获取下一步的节点
    def get_next_plan_info(self):
        url = urljoin(self.BASE_URL, "zdgl-api/bxryStrategy/bxryNode")
        data = {"processdefId": self.queryTodoBytodoId_info("processDefId"),
                "processdefName": self.queryTodoBytodoId_info("processDefName"),
                "businessId": self.queryTodoBytodoId_info("ywid"),
                "nodeId": self.queryTodoBytodoId_info("activityDefId"), "xtbs": "10011006",
                "processInstId": self.queryTodoBytodoId_info("processInstId"),
                "activityInstId": self.queryTodoBytodoId_info("activityInstId")}
        res = json.loads(self.session.post(url=url, json=data, headers=self.headers).text)
        # 检查是否成功返回和是否包含 "result" 键
        if res and "result" in res and res["result"]:
            return res["result"][0]["id"]
        else:
            # 处理请求失败或结果不符合预期的情况
            print("Failed to get next plan info.")
            return None

    # 请求下一步节点
    def requests_next_plan(self):
        url = urljoin(self.BASE_URL, "zdgl-api/bxryStrategy/bxry")
        data = {"processdefId": self.queryTodoBytodoId_info("processDefId"),
                "processdefName": self.queryTodoBytodoId_info("processDefName"),
                "businessId": self.queryTodoBytodoId_info("ywid"), "docType": "4", "xtbs": "10011006", "sqr": "",
                "sfwt": "2", "processInstId": self.queryTodoBytodoId_info("parentProcessInstId"), "activityDefId": "",
                "activityInstId": "2081", "ywbs": "100",
                "nodeId": self.next_activit}
        res = json.loads(self.session.post(url=url, json=data, headers=self.headers).text)
        return res


def run():

    JapdApi().requests_next_plan()
    JapdApi().bmnsh_plan()


if __name__ == '__main__':
    run()
